/**
 * module:  品种管理
 * avator:   渣
 * table:  nc_livestock_type
 */
var express = require('express');
var router = express.Router();
const db = require('../../../db/db');
var zSend = require('./controller');

router.get('/list', async function (req, res, next) {
    // 获取分页参数，没有则设置默认值
    let currentPage = parseInt(req.query.currentPage) || 1;
    let pageSize = parseInt(req.query.pageSize) || 5;
    const searchValue = req.query.searchValue || '';
    
    try {
        // 查询总记录数
        const countResult = await new Promise((resolve, reject) => {
            const sql = `
                select count(*) as total
                from nc_livestock_type
                where F_Title like '%${searchValue}%'
            `;
            db.query(sql, (err, result) => {
                if(err) 
                    reject(err);
                else 
                    resolve(result);
            });
        });
        
        const total = countResult.length > 0 ? countResult[0].total : 0;
        if (total === 0) {
            res.send(zSend('未找到匹配数据', 404));
            return;
        }
        // 计算当前页数，如果超过总页数则设置为最后一页
        if(currentPage > Math.ceil(total / pageSize)) {
            currentPage = Math.ceil(total / pageSize);
        }
        // 分页查询数据
        const dataResult = await new Promise((resolve, reject) => {
            const sql = `
                select *
                from nc_livestock_type
                where F_Title like '%${searchValue}%'
                limit ${(currentPage-1)*pageSize},${pageSize}
            `;
            db.query(sql, (err, result) => {
                if(err) 
                    reject(err);
                else 
                    resolve(result);
            });
        });
        
        if(dataResult.length > 0) {
            res.send({
                code: 200,
                data: {
                    total,
                    list: dataResult
                },
                msg: '搜索成功'
            });
        } else {
            res.send(zSend('未找到匹配数据', 404));
        }
    } catch(err) {
        console.error(err);
        res.send(zSend('服务器内部错误', 500));
    }
});

router.post('/add', function (req, res, next) {
    const { F_Name, F_ParentId, F_Sort } = req.body;
    if(!F_Name || !F_ParentId || !F_Sort) {
        res.send(zSend('参数错误',400));
        return;
    }
    const F_Id = Date.now();
    const sql = `
        insert into nc_livestock_type
        values(${F_Id},'${F_Name}',${F_ParentId},${F_Sort})
    `;
    db.query(sql, (err, result) => {
        if(result.affectedRows > 0) {
            res.send(zSend('添加成功'));
            return;
        } else {
            res.send(zSend('服务器内部错误',500));
            return;
        }
    });
});

router.post('/delete', function (req, res, next) {
    const { F_Id } = req.body;
    if(!F_Id) {
        res.send(zSend('参数错误',400));
        return;
    }
    const sql = `
        delete from nc_livestock_type
        where F_Id = '${F_Id}'
    `;
    db.query(sql, (err, result) => {
        if(result.affectedRows > 0) {
            res.send(zSend('删除成功'));
            return;
        } else {
            res.send(zSend('服务器内部错误',500));
            return;
        }
    });
});

router.post('/update', function (req, res, next) {
    const { F_Id, F_Name, F_ParentId, F_Sort } = req.body;
    if(!F_Id || !F_Name || !F_ParentId || !F_Sort) {
        res.send(zSend('参数错误',400));
        return;
    }
    const sql = `
        update nc_livestock_type
        set F_Title = '${F_Name}', F_ParentId = '${F_ParentId}', F_Sort = ${F_Sort}
        where F_Id = '${F_Id}'
    `;
    
    db.query(sql, (err, result) => {
        if(result.affectedRows > 0) {
            res.send(zSend('修改成功'));
            return;
        } else {
            res.send(zSend('服务器内部错误',500));
            return;
        }
    });
});

module.exports = router;